package com.aioz.service.impl;

import com.aioz.entity.Goods;
import com.aioz.entity.Purchase;
import com.aioz.entity.User;
import com.aioz.mapper.GoodsMapper;
import com.aioz.service.GoodsService;
import com.aioz.utils.RedisIdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;


@Service
public class GoodsServiceImpl extends ServiceImpl<GoodsMapper, Goods> implements GoodsService {

    private static final Logger log = LoggerFactory.getLogger(GoodsServiceImpl.class);

    @Resource
    private RedisIdWorker redisIdWorker;

    @Resource
    private PurchaseServiceImpl purchaseService;

    @Resource
    private UserServiceImpl userService;

    @Override
    public void purchaseGoods(Long userId,Integer goodsId) {
        log.info("开始扣减库存");
        User user = userService.query().eq("id", userId).one();
        Goods goods = query().eq("id", goodsId).one();
        boolean isSuccess = update().eq("id", goodsId).setSql("stock = stock - 1").update();
        if(isSuccess){
            long purchaseId = redisIdWorker.nextId("order");
            Purchase purchase = new Purchase();
            purchase.setId(purchaseId);
            purchase.setCard(user.getId());
            purchase.setBuyer(user.getUsername());
            purchase.setCommodity(goods.getName());
            purchaseService.save(purchase);
            log.info("扣减成功! 生成订单 {}",purchase);
        }else {
            log.info("库存不足!");
        }
    }
}
